<?php

namespace App\Http\Middleware;

use Closure;
use Intervention\Image\Facades\Image;

class ImageResizeMiddleware {

    public function handle($request, Closure $next)
    {
        $path = $request->path();
        $uri = $request->getRequestUri();

        $path = str_replace('images', '', $path);
        $file = config('filesystems.disks.image.root').$path;

        $hash = substr(md5($uri), 0 , 2);

        if (preg_match("/(^.*).(png|jpg|jpeg|gif)\?(\d+)x(\d+)/i", $uri, $match)) {
            $toPath = '/'.$hash.'/'.md5($uri).'.'.$match[2];
            $toFile = config('filesystems.disks.image.root').$toPath;

            if(file_exists($toFile))
            {
                if(file_exists(public_path('image'.$toPath)))
                {
                    return response()->redirectTo('image'.$toPath);
                }

            }
            if (file_exists($file)) {
                $width = intval($match[3]);
                $height = intval($match[4]);


                if ($width && $height) {
                    $im = Image::make($file)->fit($width ? $width : null, $height ? $height : null, function($constraint) {
                        $constraint->upsize();
                    });
                } else {
                    $im = Image::make($file)->resize($width ? $width : null, $height ? $height : null, function($constraint) {
                        $constraint->aspectRatio();
                        $constraint->upsize();
                    });
                }

                try {
                    $pathInfo = pathinfo($toFile);
                    if(!is_dir($pathInfo['dirname']))
                    {
                        mkdir($pathInfo['dirname']);
                    }
                    $im->save($toFile, 70);
                } catch (\Exception $e) {
                    // I don't care.
                }
                if(file_exists(public_path('image'.$toPath)))
                {
                    return response()->redirectTo('image'.$toPath);
                }
            }
        }elseif(preg_match("/(^.*).(png|jpg|jpeg|gif)$/i", $uri))
        {
            $toPath = $path[0] == '/'? 'image'.$path:'image/'.$path;
            if(file_exists(public_path($toPath)))
            {
                return response()->redirectTo($toPath);
            }
        }


        return $next($request);
    }
}